<template>
  <!--  -->
  <div class="form-item-box">
    <div class="item-label">
      {{ label }}
    </div>
    <div><slot></slot></div>
    <div class="err-tip">
      <span v-show="showError">{{
        tipMessage || rule?.message || label + "必填" || prop + "必填"
      }}</span>
    </div>
  </div>
</template>

<script setup>
import $common from "@/utils/$common";
import { getCurrentInstance, onMounted, onBeforeUnmount, watch } from "vue";

const { ctx } = getCurrentInstance();

const props = defineProps({
  label: {
    default: "",
  },
  prop: {
    default: "",
  },
  rule: {
    default: () => {
      return {
        message: "",
      };
    },
  },
  labelWidth: {
    default: "100rpx",
  },
});

onMounted(() => {
  ctx.ctxId = Date.now();
  ctx.validatorChild = validatorChild;
  ctx.$parent.getChild(ctx);
});

onBeforeUnmount(() => {
  ctx.$parent.delChild(ctx);
});

let showError = $ref(false);
let tipMessage = $ref("");
function validatorChild(data) {
  tipMessage = "";
  return new Promise((resolve, reject) => {
    console.log(data);
    let validatorFn = props.rule.validator;
    if (!data) {
      showError = true;
      resolve(props.rule);
    } else if (["array", "Array"].includes(props.rule.type) && !data.length) {
      showError = true;
      resolve(props.rule);
    } else if (validatorFn) {
      function callBack(msg) {
        tipMessage = msg;
        if (msg) {
          showError = true;
          resolve(props.rule);
        } else {
          showError = false;
          resolve(false);
        }
      }
      validatorFn($common.deepCopy(data), callBack);
    } else {
      showError = false;
      resolve(false);
    }
  });
}
</script>
<style lang="scss" scoped>
.form-item-box {
  margin-bottom: 20rpx;
  .err-tip {
    color: red;
    font-size: 24rpx;
    height: 28rpx;
    line-height: 28rpx;
  }
}
</style>
